package com.ys.web.ws.manager;

import com.aliyun.openservices.shade.io.netty.util.internal.ConcurrentSet;
import com.ys.web.ws.ChatObject;
import io.vertx.core.http.ServerWebSocket;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ 名称:聊天连接管理器
 * @ 创建人: dhf
 * @ 参数： null
 * @ 创建时间: 2022/5/11
 * @ 修改人和其它信息
 * @ 返回值:
 */
@Slf4j
public class ChatObjectManager {

    private static boolean flag = false;

    private ChatObjectManager() {
        synchronized (ChatObjectManager.class) {
            //方式反射创建新的实例
            if (flag) {
                throw new RuntimeException("无法创建多个对象");
            }
            flag = true;
        }
    }

    //建立 websocket 连接后 讲对象存入Map中
    /**
     * websocket 连接内存 存储容器
     */
    public static ConcurrentHashMap<String, ChatObject> chatMap = new ConcurrentHashMap<>();

    private static class ChatObjectManagerHolder {
        // 保存每一个连接到服务器的通道
        private static final ConcurrentHashMap<String, ServerWebSocket> CONCURRENT_HASH_MAP = new ConcurrentHashMap<>(16);

        // 保存每一个连接到服务器用户的时间
        private static final ConcurrentHashMap<String, Long> CONCURRENT_HASH_MAP_TIME = new ConcurrentHashMap<>(16);

        // 保存还有未读消息的用户id
        private static final ConcurrentSet<Long> CONCURRENT_UNREAD_SET = new ConcurrentSet<>();
    }


    public static ConcurrentHashMap<String, ServerWebSocket> getConnectionMap() {
        return ChatObjectManagerHolder.CONCURRENT_HASH_MAP;
    }

    public static ConcurrentHashMap<String, Long> getConnectionMapTime() {
        return ChatObjectManagerHolder.CONCURRENT_HASH_MAP_TIME;
    }

    public static ConcurrentSet<Long> getConnectionUnReadPage() {
        return ChatObjectManagerHolder.CONCURRENT_UNREAD_SET;
    }

    //防止序列化产生不同的map
    public Object readResolve() {
        return ChatObjectManagerHolder.CONCURRENT_HASH_MAP;
    }

    /**
     * 移除连接
     *
     * @param key userId
     */
    public synchronized static void removeChatMapByKey(String key) {
        getConnectionMap().remove(key);
        getConnectionMapTime().remove(key);
//        Logger.info("移除map");
        getCurrentOnline();
    }

    /**
     * 获取当前在线人数
     */
    public static void getCurrentOnline() {
//        log.info("当前在线人数 Map 数据：" + getConnectionMap().size());
//        log.info("当前在线用户列表：{}", JsonUtil.toJson(getConnectionMap().entrySet().parallelStream().map(x -> McodeHandler.from32Radix(x.getKey())).collect(Collectors.toList())));
    }
}
